let cnst = require('./../const');

const mysqlPool = require('./MySQLPool');
const dateUtil = require('./../util/dateUtil')
const field = ["account", "name", "phone", "uid", "weixinUid"];
const {BusiError, SysError} = require('../exception/exception');
class UserDao {
    constructor() { }

    /**
     * 通用方法，条件搜索
     * @param user
     * @returns {Promise<*>}
     */
    async getUserByCondition(user){
        let sql = 'select * from  users where 1 = 1 ';
        let args = [];
        for(let i = 0; i< field.length; i++){
            let key = field[i];
            if(user[key] && user[key] !== undefined){
                sql = sql + "and " + field[i] + "=? ";
                args.push(user[key]);
            }
        }
        console.logw("sql:" + sql + ",args:" + args);
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getUserByAccountOrWeixinUid(user){
        console.logg("getUserByAccountOrWeixinUid",user)
        let sql = 'select * from  users where account=? or weixinUid=? ';
        let  args=[user.account,user.weixinUid]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getUserByAccountOrXianliaoUid(user){
        console.logg("getUserByAccountOrWeixinUid",user)
        let sql = 'select * from  users where account=?';
        let  args=[user.account]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    /**
     * Get userInfo by username
     * @param {String} username
     * @param {function} cb
     */
    async getUserByName(username, cb) {
        let sql = 'select * from  User where name = ?';
        let args = [username];
        await mysqlPool.query(sql, args).then(res => {
            if (!!res && res.length === 1) {
                let rs = res[0];
                let user = { id: rs.id, name: rs.name, password: rs.password, from: rs.from, diamond: rs.diamond, coin: rs.coin, phone: rs.phone, email: rs.email, sex: rs.sex };
                cb(null, user);
            } else {
                cb(' user not exist ', null);
            }
        }).catch(err => {
            cb(err.message, null);
        });
    }

    //select * from information_schema.tables where TABLE_SCHEMA='gamedald' and TABLE_NAME='sysinfo';
    //select * from user limit 3,4;
    async pgetUserByName(username) {
        let sql = 'select * from  User where name = ?';
        let args = [username];
        try {
            let res = await mysqlPool.query(sql, args);
            let user = null;
            if (!!res && res.length === 1) {
                let rs = res[0];
                user = rs;
                //user= {id: rs.id, name: rs.name, password: rs.password, from: rs.from,diamond:rs.diamond,coin:rs.coin,phone:rs.phone,email:rs.email,sex:rs.sex};
            }
            return user;
        } catch (e) {
            let n = 0;
            n++;
            return null;
        }

    }

    async pgetTableRowCount(dbName, tableName) {
        let sql = 'select * from information_schema.tables where TABLE_SCHEMA=? and TABLE_NAME=?';
        let args = [dbName, tableName];
        try {
            let res = await mysqlPool.query(sql, args);
            if (!!res && res.length === 1) {
                let rs = res[0];
                return rs.TABLE_ROWS;
            }
            return 0;
        } catch (e) {
            return 0;
        }
    }
    //select * from user limit 3,4;
    async pgetRowsByRange(tableName, index, count) {
        if (count <= 0)
            return 0;
        let sql = 'select * from ' + tableName + ' limit ' + index + ',' + (index + count);
        let args = [tableName, index, index + count];
        try {
            let res = await mysqlPool.query(sql, args);

            return res;
        } catch (e) {
            return 0;
        }
    }

    async psysInfoAddRecord(imgName) {
        let sql = 'insert into sysinfo (imgName) values(?)';
        let args = [imgName];
        try {
            let res = await mysqlPool.query(sql, args);
            if (!res) {
                return { id: res.insertId };
            }
            return null;
        } catch (e) {
            return null;
        }
    }

    async psysInfoGetRecord(imgName) {
        let sql = 'select * from sysinfo where imgName=?';
        let args = [imgName];
        try {
            let res = await mysqlPool.query(sql, args);
            if (!!res && res.length === 1) {
                let rs = res[0];
                return rs;
            }
            return null;
        } catch (e) {
            return null;
        }
    }

    async psysInfoDelRecord(id) {
        let sql = 'delete from sysinfo where id=?';
        let args = [id];
        try {
            let res = await mysqlPool.query(sql, args);
            if (!!res && res.length === 1) {
                let rs = res[0];
                return rs;
            }
            return null;
        } catch (e) {
            return null;
        }
    }

    /**
     * Create a new user
     * @param (String) username
     * @param {String} password
     * @param {String} from Register source
     * @param {function} cb Call back function.
     */
    async createUser(username, password, from, cb) {
        let sql = 'insert into User (name,password,`from`,loginCount,lastLoginTime) values(?,?,?,?,?)';
        let loginTime = Date.now();
        let args = [username, password, from || '', 1, loginTime];
        await mysqlPool.query(sql, args).then(res => {
            let userId = res.insertId;
            let user = { id: res.insertId, name: username, password: password, loginCount: 1, lastLoginTime: loginTime };
            cb(null, user);
        }).catch(err => {
            cb({ code: err.number, msg: err.message }, null);
        });
    }

    RandomUid(len) {
        let $chars = '0123456789';
        let maxPos = $chars.length;
        let pwd = ''; 
        for (let i = 0; i < len; i++) { 
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); 
            pwd = Number(pwd);

            pwd += "";
        }
        return pwd;
    }
    // async createWxUserAsync(account, name, headimgurl, sex, ip, wxNickName) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let record = await async isUserExitAsync(account);
    //     if (record != null && record.length > 0) {
    //         let id = record[0].Id;
    //         let sql = 'update users set name=?,wxNickName=?,headimgurl=?,sex=?,lastLoginTick=? where id=?';
    //         let args = [name, wxNickName, headimgurl, sex, Date.now(), id];
    //         console.logw('update users ', args);
    //         let res = await mysqlPool.query(sql, args);
    //         let suc = false;
    //         if (res) { suc = true; }
    //         let info = record[0];
    //         info.suc = suc;
    //         return info;
    //     }
    //     let uid = RandomUid(6);
    //     let sql = 'select max(Id) FROM users';
    //     let res = await mysqlPool.query(sql, []);
    //     let uid = res[0]['max(Id)'] + 100000;
    //     let sql = 'insert into users (account,name,wxNickName,headimgurl,sex,lastLoginTick,uid,registerDate,registerIp) values(?,?,?,?,?,?,?,?,?)';

    //     let loginTime = new Date().getTime();
    //     let args = [account, name, wxNickName, headimgurl, sex, loginTime, uid, new Date(), ip];
    //     console.logw('insert users ', args);
    //     let res = await psql.insertAsync(sql, args);
    //     let user = null;
    //     if (res) {
    //         let Id = res.insertId;
    //         return { suc: true, uid: uid, wxNickName: wxNickName };
    //     }
    //     return null;
    // });

    async getOrCreateUserAccessAsync(uid, name) {
        let sql = 'select * from access_control where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res != null && res.length > 0) {
            return res[0];
        }

        sql = 'insert into access_control (uid,name) values(?,?)';
        args = [uid, name];
        res = await mysqlPool.query(sql, args);
        return res;
    }

    async updateUserUid(id) {
        let sql = 'update users set uid=? where id=?';
        let uid = this.RandomUid(6);
        let args = [uid, id];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async createAliRequestOrder(user_id, order_id, total_amount, timestamp) {
        let sql = 'insert into request_order (order_id,total_amount,timestamp,user_id) values(?,?,?,?)';
        let args = [order_id, total_amount, timestamp, user_id];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }

    async createWxRequestOrder(user_id, order_id, total_amount, timestamp) {
        let sql = 'insert into request_order (order_id,total_amount,timestamp,user_id,pay_channel) values(?,?,?,?,?)';
        let args = [order_id, total_amount, timestamp, user_id, "weixin"];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }

    //充值钱发起的订单
    async createPay4RequestOrder(user_id, order_id, total_amount, timestamp, sign) {
        let sql = 'insert into request_order (order_id,total_amount,timestamp,user_id,check_sign) values(?,?,?,?,?)';
        let args = [order_id, total_amount, timestamp, user_id, sign];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }

    //充值后确认的订单
    async createPay4RechargeOrder(user_id, order_id, total_amount, timestamp, sign) {
        //首先从请求的订单中确认是否sign是有效的
        let sql = 'select * from request_order where order_id=?';
        let args = [order_id];
        let res = await mysqlPool.query(sql, args);
        if (!res) {
            console.log('can not find order ', order_id);
            return null;
        }
        if (res.length === 0) {
            console.log('can not find order ', order_id);
            return null;
        }
        if (res[0].order_id !== order_id) {
            console.log('check order_id failed ', res[0].order_id, order_id);
            return null;
        }
        if (res[0].total_amount !== total_amount) {
            console.log('check total_amount failed ', res[0].total_amount, total_amount);
            return null;
        }
        sql = 'insert into recharge (order_id,total_amount,time,user_id,check_sign) values(?,?,?,?,?)';
        args = [order_id, total_amount, timestamp, user_id, sign];
        let res1 = await mysqlPool.query(sql, args);
        let user = null;
        if (res1) {
            let Id = res1.insertId;
            return { suc: true, id: Id, totao_amount: res[0].total_amount };
        }
        console.log('insert into recharge failed createPay4RechargeOrder');
        return null;
    }


    //创建充值订单
    async createAliRechargeOrder(user_id, order_id, total_amount, timestamp, name) {
        let sql = 'insert into recharge (user_id,order_id,total_amount,addCardNum,time,user_name) values(?,?,?,?,?,?)';
        let cardNum = Number(total_amount) * cnst.cardsPerRMB;
        let args = [user_id, order_id, total_amount, cardNum, timestamp, name];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }


    //创建充值订单
    async createWxShewawaRechargeOrder(user_id, order_id, total_amount, timestamp) {
        let sql = 'insert into recharge (user_id,order_id,total_amount,addCardNum,time) values(?,?,?,?,?)';
        let map = { 6.9: 70, 28: 380, 100: 1400, 200: 2800 };
        let rmb = total_amount;
        let diamond = map[rmb];
        if (diamond === undefined) {
            diamond = rmb * 10;
        }
        let tick = Number(timestamp) * 1000;
        console.logg("玩家充值 " + rmb + " 获得钻石" + diamond);
        let time = this.getTimeByTick(tick);
        let args = [user_id, order_id, total_amount, diamond, time];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            res.diamond = diamond;
            res.time = time;
            res.total_amount = total_amount;
            return res;
        }
        return null;
    }


    async buyCard(price) {
        price = Number(price);
        if (price < 0) return 0;
        price = price * cnst.cardDebugArg;
        let cardNum = cnst.rechargeMap[price];
        cardNum = Math.round(cardNum * cnst.wxPay4_rechageRate);
        if (cardNum) return cardNum;
        // return 1;
        let len = cnst.rechargeRate.length;
        for (let i = 0; i < len; i++) {
            let it = cnst.rechargeRate[i];
            if (price > it.min && price < it.max) return Math.round(price * it.rate);
        }
        return 0;
    }

    async buyCard_wx(price) {
        price = Number(price);
        if (price < 0) return 0;
        let cardNum = cnst.wx_rechargeMap[price];
        console.log('buyCard_wx', price, cardNum);
        if (cardNum === undefined) return 0;
        return cardNum;
    }

    async buyCard_ali(price) {
        price = Number(price);
        if (price < 0) return 0;
        let cardNum = cnst.ali_rechargeMap[price];
        console.log('buyCard_ali', price, cardNum);
        if (cardNum === undefined) return 0;
        if (cardNum) return cardNum;
    }

    async addUserCardNum(user_id, cardNum) {
        let sql = 'select * from users where uid=?';
        let args = [user_id];
        console.log('add user card uid', user_id);
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0 || cardNum < 0) { return null; }
        let info = res[0];
        info.cardNum += cardNum;
        sql = 'update users set cardNum=? where uid=?';
        args = [info.cardNum, user_id];
        console.log('user ', info.name, info.cardNum, '增加房卡', cardNum);
        let res0 = await mysqlPool.query(sql, args);
        if (!res0)
            return null;
        res0.userInfo = info;
        return res0;
    }

    // async decreaseUserCard(uid, deNum) {
    //     let ret = await async decCardSafeAsync(uid, deNum);
    //     return ret;
    // });

    // async addCardSafeAsync(uid, addNum) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from users where uid=?';
    //         let args = [uid];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let info = res[0];
    //         //info.cardNum+=Math.floor(Math.abs(addNum));
    //         info.cardNum += Math.floor(addNum);
    //         console.logg('增加玩家 ', uid, info.name, addNum, '房卡 剩余', info.cardNum);
    //         if (info.cardNum < 0) info.cardNum = 0;
    //         sql = 'update users set cardNum=? where uid=?';
    //         args = [info.cardNum, uid];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }

    // });


    async addCoinSafeAsync(uid, addNum, event) {
        let sql = 'select * from users where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return null;
        }

        let info = res[0];
        //info.cardNum+=Math.floor(Math.abs(addNum));
        let coinNum = info.coinNum;
        info.coinNum += Number(addNum);
        info.preCoinNum = coinNum;
        console.logw('玩家原有', coinNum, "游戏币 ", uid, info.name, "增加 ", addNum, '游戏币 剩余', info.coinNum);
        if (info.coinNum < 0) {
            info.coinNum = 0;
            console.logg('玩家 ', uid, info.name, addNum, '游戏币 变为负的，清零', info.coinNum);
        }

        sql = 'update users set coinNum=? ,updateEvent=? where uid=?';
        args = [info.coinNum, event, uid];
        if (!event) {
            sql = 'update users set coinNum=? where uid=?';
            args = [info.coinNum, uid];
        }

        await mysqlPool.query(sql, args);
        return info;
    }

    async updateCoins(uid, event, coins){
        let sql = 'update users set coinNum = (coinNum + ?), updateEvent = ? where uid = ?';
        let args = [coins, event, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res.affectedRows;
        }
        return 0;
    }

    async updateBuffer(uid, event, coins){
        let sql = 'update users set buffer = (buffer + ?), updateEvent = ? where uid = ?';
        let args = [coins, event, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res.affectedRows;
        }
        return 0;
    }

    
    async updateFlag(uid, event, flag){
        let sql = 'update users set debugFlag = ?, updateEvent = ? where uid = ?';
        let args = [flag, event, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res.affectedRows;
        }
        return 0;
    }


    // async coin2Bank(uid, coin) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from users where uid=?';
    //         let args = [uid];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let info = res[0];
    //         //info.cardNum+=Math.floor(Math.abs(addNum));
    //         let coinNum = info.coinNum;
    //         info.coinNum -= Number(coin);
    //         if (info.coinNum < 0) {
    //             console.logg('非法的操作玩家游戏币变为负数', coinNum, coin);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         info.bankCoin += Number(coin)
    //         info.preCoinNum = coinNum;
    //         console.logw('玩家原有', coinNum, "游戏币 ", uid, info.name, "减少 ", coin, 'bankCoin变为', info.bankCoin);
    //         let sql = 'update users set coinNum=?,bankCoin=? where uid=?';
    //         let args = [info.coinNum, info.bankCoin, uid];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });


    async getUserInfoByUid(uid) {
        // let sql = 'select  uid, name, phone, cardNum,coinNum, bankCoin, registerIp, registerDate, lastLoginDate, isAgent, ' +
        //     'headimgurl, sex, freezeCoin, code ,buff,from users where uid = ? limit 1';
        let  sql="select * from users where uid=?";
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0];
        }
        return null;
    }

    async setUserToAgentWithTx(conn, uid) {
        let sql = 'update users set isAgent = 1 where uid = ?';
        let args = [uid];
        let res = await conn.query(sql, args);
        if (res) {
            return res.affectedRows;
        }
        return null;
    }

    /**
     * 
     * @param {MySQLConn} conn 
     * @param {String} uid 
     * @param {String} code 
     */
    async setUserAgentCodeWithTx(conn, uid, code) {
        let sql = 'update users set code = ? where uid = ?';
        let args = [code, uid];
        let res = await conn.query(sql, args);
        if (res) {
            return res.affectedRows;
        }
        return null;
    }

    /**
     * @param {String} uid
     */
    async getUserByUid(uid) {
        let sql = 'select * from users where uid = ? limit 1';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res[0];
        }
        return null;
    }

    //快3 获取战绩
    async getMyK3Record(uid,typePlace,typeAward,page){
        let sql = 'select * from admin_playerwin where uid = ?';

        let args = [];
        args.push(uid);
    
        if (typePlace != 2){
            sql += ' and gameType = ?'
            args.push(typePlace);
        }
        if (typeAward == 0){
            sql += ' and winCoins >= 0'
        }else if(typeAward == 1){
            sql += ' and winCoins < 0'
        }
        let offset = (page - 1) * 7;
        if (offset < 0) offset = 0;
        sql += ' order by id desc limit ' + offset + ',7';
        
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res;
        }
        return null;
    }
    async getMyK3RecordCount(uid,typePlace,typeAward){

        let sql = 'select count(1) from admin_playerwin where uid = ?';

        let args = [];
        args.push(uid);
    
        if (typePlace != 2){
            sql += ' and gameType = ?'
            args.push(typePlace);
        }
        if (typeAward == 0){
            sql += ' and winCoins >= 0'
        }else if(typeAward == 1){
            sql += ' and winCoins < 0'
        }
     
        let res = await mysqlPool.query(sql, args);
        if (res){
           return res[0]['count(1)']
        }
        return 0;
    }

    //历史总金额
    async getAdminAllScore(uid){
        let sql = 'select score from admin_all_yield where uid = ?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res[0];
        }
        return null;
    }

    //昨日金额及人数
    async getAdminYDayInfo(uid){
        let sql = 'select * from admin_day_yield where uid = ? and to_days(now()) - to_days(createTime) = 1';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res[0];
        }
        return null;
    }
    //可领取金额
    async getAdminYCanScore(uid){
        let sql = 'select score from admin_leader_yield where uid = ?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res[0];
        }
        return null;
    }
    //今天人数
    async getAdminDCanScore(uid){
        // let sql = 'select count(1) from admin_playerwin where to_days(now()) - to_days(createTime) = 1 group by uid;';
        // let args = [uid];
        // let res = await mysqlPool.query(sql, args);
        // if (res && res.length >0) {
        //     return res[0];
        // }
        return 0;
    }
    //领取奖励
    async getk3AdminAward(uid){
        let sql = 'select * from admin_leader_yield where uid = ?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            if(res[0].score > 0){
                let sql2 = 'update admin_leader_yield set score = 0 where uid = ?';
                let res2 = await mysqlPool.query(sql2, args);
                if (res2){
                    //玩家加上金币
                    let sql3 = 'update users set coinNum = coinNum + ? where uid = ?';
                    let args3 = [res[0].score,uid];
                    let res3 = await mysqlPool.query(sql3, args3);
                    if(res3){
                        //记录一下
                        let sql4 = 'insert into admin_transfer (kind,fromId,toId,score,oriScore,createTime) values (1,?,?,?,?,now())';
                        let args4 = [uid,uid,res[0].score,res[0].score];
                        let res4 = await mysqlPool.query(sql4, args4);
                        return '领取成功';
                    }
                }else{
                    return '领取失败';
                }
            }else{
                return '领取失败';
            }
        }
        return '领取失败';
    }

    //推广明细
    //0 1 2 今月 上月 全部
    async getk3AdminInfo(uid,mType,page){
        let sql = 'select * from admin_transfer where toId = ?';
        if(mType == 0){
            sql += ' and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
        }else if(mType == 1){
            sql += ' and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1'
        }
        let offset = (page - 1) * 14;
        if (offset < 0) offset = 0;

        sql += ' and kind = 0 order by id desc limit ' + offset + ',14';
        let args = [uid];

        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res;
        }
        return null;

    }
    async getk3AdminInfoCount(uid,mType){
        let sql = 'select count(1) from admin_transfer where toId = ?';

        if(mType == 0){
            sql += ' and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
        }else if(mType == 1){
            sql += ' and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1'
        }
        sql += ' and kind = 0';
        let args = [uid];
    
        let res = await mysqlPool.query(sql, args);
        if (res){
           return res[0]['count(1)']
        }
        return 0;
    }

    async getk3ScoreInfoCount(uid,mType){
        let sql = 'select count(1) from admin_transfer where toId = ?';
        if(mType == 0){
            sql += ' and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
        }else if(mType == 1){
            sql += ' and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1'
        }

        let args = [uid];

        let res = await mysqlPool.query(sql, args);
        if (res){
           return res[0]['count(1)']
        }
        return 0;
    }

    //资金明细
    async getk3ScoreInfo(uid,mType,page){
        let sql = 'select * from admin_transfer where toId = ?';
        if(mType == 0){
            sql += ' and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
        }else if(mType == 1){
            sql += ' and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1'
        }
        let offset = (page - 1) * 14;
        if (offset < 0) offset = 0;

        sql += ' order by id desc limit ' + offset + ',14';
        let args = [uid];

        let res = await mysqlPool.query(sql, args);
        if (res && res.length >0) {
            return res;
        }
        return null;
    }
       /**
     * 用户是否存在并且为管理员级别
     */
    async getUnionUserByUid(uid,unionid) {
        let sql = 'select users.* from users INNER JOIN union_administrator ON users.uid = union_administrator.uid where users.uid = ? and union_administrator.unionId = ? limit 1';
        let args = [uid,unionid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0];
        }
        return null;
    }

    async queryUsers() {
        let sql = 'select * from users where password is not null and password != \'\'';
        let args = [];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }
        return null;
    }

    async getUserByMobile(mobile) {
        let sql = 'select * from users where phone = ? limit 1';
        let args = [mobile];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0];
        }
        return null;
    }

    async decCoinWithTx(conn, uid, coin) {
        let sql = 'update users set coinNum = (coinNum - ?) where uid=? and (coinNum - ?) >= 0';
        let args = [coin, uid+"", coin];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    /***
     * @param {String} uid
     * @param {Number} card
     */
    async decCard(uid, card) {
        //let sql = 'update users set cardNum = (cardNum - ?) where uid=? and (cardNum - ?) >= 0';
        let sql = 'update users set cardNum = (cardNum - ?) where uid=? ';
        let args = [card, uid+""];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    async decCardKou(uid, card) {
        //let sql = 'update users set cardNum = (cardNum - ?) where uid=? and (cardNum - ?) >= 0';
        let sql = 'update users set cardNum = (cardNum - ?) where uid=?';
        let args = [card, uid,card];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    async saveFkRechargeRecord(cardNum, gameType, conn) {
        if(!conn){
            conn = mysqlPool;
        }
        let date = new Date();
        let dateStr = dateUtil.dateFormatYMD(date);
        let record = await this.getFkRechargeRecordByDate(dateStr, gameType, conn);
        if(record === null){
            let sql = 'insert into day_recharge (name, time, cardNum, gameType) values (?, ?, ?, ?)';
            let args = ["day", dateStr, cardNum, gameType];
            await conn.query(sql, args);
        }else{
            let sql = 'update day_recharge set cardNum = (cardNum + ?)  where time = ? and gameType = ?';
            let args = [cardNum, dateStr, gameType];
            await conn.query(sql, args);
        }


    }

    async getFkRechargeRecordByDate(date, gameType, conn){
        if(!conn){
            conn = mysqlPool;
        }
        let sql = 'select * from day_recharge where time = ? and gameType = ?';
        let args = [date, gameType];
        let res = await conn.query(sql, args);
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }

    async addCard(uid, card) {
        let sql = 'update users set cardNum = (cardNum + ?) where uid=?';
        let args = [card, uid+""];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    //更新玩家buff
    async upateUsersBuffer(uid, buffer){
        let sql = 'update users set buffer = (buffer + ?) where uid = ?';
        let args = [buffer, uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }

        return 0;
    }

    /**
     * 
     * @param {MySQLConn} conn 
     * @param {String} uid 
     * @param {Number} coin 
     */
    async freezeCoinWithTx(conn, uid, coin) {
        let sql = 'update users set coinNum = (coinNum - ?), freezeCoin = (freezeCoin + ?) where uid=? and (coinNum - ?) >= 0';
        let args = [coin, coin, uid + "", coin];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    async restoreCoinFromFreezeWithTx(conn, uid, coin) {
        let sql = 'update users set coinNum = (coinNum + ?), freezeCoin = (freezeCoin - ?) where uid= ? and (freezeCoin - ?) >= 0';
        let args = [coin, coin, uid + "", coin];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    async releaseFreezeCoinWithTx(conn, uid, coin) {
        let sql = 'update users set freezeCoin = (freezeCoin - ?) where uid= ? and (freezeCoin - ?) >= 0';
        let args = [coin, uid + "", coin];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    async incCoinWithTx(conn, uid, coin) {
        let sql = 'update users set coinNum = (coinNum + ?) where uid = ?';
        let args = [coin, uid];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    async incCoin(uid, coin) {
        let sql = 'update users set coinNum = (coinNum + ?) where uid = ?';
        let args = [coin, uid];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    /**
     * @param {MySQLConn} conn
     * @param {String} uid
     * @param {Number} card
     */
    async incCardWithTx(conn, uid, card) {
        let sql = 'update users set cardNum = (cardNum + ?) where uid = ?';
        let args = [card, uid];
        let res = await conn.query(sql, args);
        return res.affectedRows;
    }

    async getCoinWithTx(conn, uid) {
        let sql = 'select coinNum from users where uid=?';
        let args = [uid];
        let res = await conn.query(sql, args);
        return res[0].coinNum;
    }

    async getCoin(uid) {
        let sql = 'select coinNum from users where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        return res[0].coinNum;
    }

    async updateAvatar(uid, avatar) {
        let sql = 'update users set headimgurl = ? where uid = ?';
        let args = [avatar + "", uid];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    async updateQrcode(uid, qrcode) {
        let sql = 'update users set cdnImgurl = ? where uid = ?';
        let args = [qrcode + "", uid];
        let res = await mysqlPool.query(sql, args);
        return res.affectedRows;
    }

    /**
     *
     * @param cond
     *      cond.uid
     *      cond.name
     *      cond.phone
     *      cond.startTime
     *      cond.endTime
     * @returns {Promise<*>}
     */
    async queryByCond(cond) {
        let sql = 'select uid, name, phone, coinNum, bankCoin, registerIp, ' +
            ' registerDate, isAgent, headimgurl, sex, freezeCoin from users where 1=1 ';
        let args = [];
        if (cond.uid) {
            args.push(cond.uid);
            sql += ' and uid = ?';
        }

        if (cond.status) {
            // args.push(cond.status)
            // sql += ' and e.status = ?'
        }

        if (cond.name) {
            args.push(cond.name);
            sql += ' and name = ?';
        }

        if (cond.phone) {
            args.push(cond.phone);
            sql += ' and phone = ?';
        }

        if (cond.startTime) {
            args.push(cond.createTime);
            sql += ' and registerDate >= ?';
        }

        if (cond.endTime) {
            args.push(cond.endTime);
            sql += ' and registerDate <= ?';
        }

        sql += ' order by registerDate desc ';

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }

        return null;
    }

    /**
     *
     * @param cond
     *      cond.uid
     *      cond.name
     *      cond.phone
     *      cond.startTime
     *      cond.endTime
     * @returns {Promise<*>}
     */
    async queryPageByCond(cond) {
        let sql = 'select uid, name, phone, coinNum, bankCoin, registerIp, ' +
            ' registerDate, isAgent, headimgurl, sex, freezeCoin, ifnull(buffer, 0) buffer, debugFlag flag from users where 1=1 ';
        let args = [];
        if (cond.uid) {
            args.push(cond.uid);
            sql += ' and uid = ?';
        }

        if (cond.status) {
            // args.push(cond.status)
            // sql += ' and e.status = ?'
        }

        if (cond.name) {
            args.push(cond.name);
            sql += ' and name = ?';
        }

        if (cond.phone) {
            args.push(cond.phone);
            sql += ' and phone = ?';
        }

        if (cond.startTime) {
            args.push(cond.createTime);
            sql += ' and registerDate >= ?';
        }

        if (cond.endTime) {
            args.push(cond.endTime);
            sql += ' and registerDate <= ?';
        }

        sql += ' order by registerDate desc ';

        if (!cond.page) cond.page = 1;
        if (!cond.count) cond.count = 10;

        args.push((cond.page - 1) * cond.count);
        args.push(cond.count);
        sql += ' limit ?, ?';

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }

        return null;
    }

    async queryPageCntByCond(cond) {
        let sql = 'select count(1) cnt from users where 1=1 ';
        let args = [];
        if (cond.uid) {
            args.push(cond.uid);
            sql += ' and uid = ?';
        }

        if (cond.status) {
            // args.push(cond.status)
            // sql += ' and e.status = ?'
        }

        if (cond.name) {
            args.push(cond.name);
            sql += ' and name = ?';
        }

        if (cond.phone) {
            args.push(cond.phone);
            sql += ' and phone = ?';
        }

        if (cond.startTime) {
            args.push(cond.createTime);
            sql += ' and registerDate >= ?';
        }

        if (cond.endTime) {
            args.push(cond.endTime);
            sql += ' and registerDate <= ?';
        }

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0].cnt;
        }

        return 0;
    }


    // async bank2Coin(uid, coin) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from users where uid=?';
    //         let args = [uid];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let info = res[0];
    //         //info.cardNum+=Math.floor(Math.abs(addNum));
    //         let coinNum = info.coinNum;
    //         info.bankCoin -= Number(coin);
    //         if (info.bankCoin < 0) {
    //             console.logg('非法的操作玩家游戏币变为负数', coinNum, coin);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         info.coinNum += Number(coin)
    //         info.preCoinNum = coinNum;
    //         console.logw('bank2Coin 玩家原有', coinNum, "游戏币 ", uid, info.name, "增加 ", coin, 'bankCoin变为', info.bankCoin);
    //         let sql = 'update users set coinNum=?,bankCoin=? where uid=?';
    //         let args = [info.coinNum, info.bankCoin, uid];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });

    async insertWinRecord(uid, name, totalCoin, addCoin, gameType, date, roomId, gameTime) {
        let sql = 'insert into win_lost_record (uid,name,leftCoin,changeCoin,gameType,utime,roomId, gameTime) ' +
            ' values                           (?,  ?,   ?,       ?,         ?,       ?,    ?,      ?)';
        let args = [uid, name, Number(totalCoin), Number(addCoin), gameType, date, roomId + "", gameTime];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }


    async addDiamondSafeAsync(uid, addNum) {
        uid = "" + uid;
        return await mysqlPool.doWithTx(async (conn) => {
            let sql = 'select * from users where uid=?';
            let args = [uid];
            let res = await conn.query(sql, args);
            if (!res || res.length === 0) {
                console.logg("addDiamondSafeAsync uid no exit ", uid);
                return null;
            }

            let info = res[0];
            info.uid = uid;
            //info.cardNum+=Math.floor(Math.abs(addNum));
            info.diamond += Math.floor(addNum);
            console.logg('增加玩家 ', uid, info.name, addNum, '钻石 剩余', info.diamond);
            if (info.cardNum < 0) info.cardNum = 0;
            sql = 'update users set diamond=? where uid=?';
            args = [info.diamond, uid];
            console.logg('args  ', args);
            res = await mysqlPool.query(sql, args);

            return info;
        });
    }

    // async incDayRecharge(name, uid, time, num) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     uid = "" + uid;
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from day_recharge where name=? and time=?';
    //         let args = [name, time];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             sql = 'insert into day_recharge (name,time,cardNum,uid) values(?,?,?,?)';
    //             let args = [name, time, num, uid];
    //             res = await cli.queryAsync(sql, args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             res.cardNum = num;
    //             return res;
    //         }
    //         let info = res[0];
    //         info.cardNum = Number(info.cardNum) + Number(num);
    //         console.logg('今日充值 ', uid, name, num, '房卡 总数', info.cardNum, time);
    //         let sql = 'update day_recharge set cardNum=? where uid=? and time=?';
    //         let args = [info.cardNum, uid, time];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         console.logg('error incDayRecharge', e.message);
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });

    // async incDayCard(name, uid, time, num) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from dayconsume where uid=? and time=?';
    //         let args = [uid, time];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             sql = 'insert into dayconsume (name,time,cardNum,uid) values(?,?,?,?)';
    //             let args = [name, time, num, uid];
    //             res = await cli.queryAsync(sql, args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             res.cardNum = num;
    //             return res;
    //         }
    //         let info = res[0];
    //         info.cardNum += num;
    //         console.logg('玩家今日消费 ', uid, name, num, '房卡 剩余', info.cardNum);
    //         let sql = 'update dayconsume set cardNum=? where uid=? and time=?';
    //         let args = [info.cardNum, uid, time];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         console.logg('error incDayCard', e.message);
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }

    // });

    // async decCardSafeAsync(uid, deNum) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from users where uid=?';
    //         let args = [uid];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let info = res[0];
    //         info.cardNum -= deNum;
    //         console.logg('扣除玩家 ', uid, info.name, deNum, '房卡 剩余', info.cardNum);
    //         info.shortCard = 0;
    //         if (info.cardNum < 0) { info.cardNum = 0; info.shortCard = 1; }
    //         let sql = 'update users set cardNum=? where uid=?';
    //         let args = [info.cardNum, uid];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }

    // });

    async queryAliRechargeOrder(user_id) {
        let sql = 'select * from  recharge where user_id=?';
        let args = [user_id];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res; }
        return null;
    }

    async queryAliRequestOrder(user_id) {
        let sql = 'select * from  request_order where user_id=?';
        let args = [user_id];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res; }
        return null;
    }

    async queryAliRechargeOrderByOrder(order_id) {
        let sql = 'select * from  recharge where order_id=?';
        let args = [order_id];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res; }
        return null;
    }

    async queryAliRequestOrderByOrder(order_id) {
        let sql = 'select * from  request_order where order_id=?';
        let args = [order_id];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res[0]; }
        return null;
    }

    async isUserExitAsync(account) {
        let sql = 'select * from  users where account=?';
        let args = [account];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            let len = res.length;
            if (len === 0) return null;
            return res;
        }
        return null;
    }

    async getUserByAccount(account) {
        let sql = 'select * from  users where account=?';
        let args = [account];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            let len = res.length;
            if (len === 0) return null;
            return res[0];
        }
        return null;
    }

    async getUserByIdAsync(uid) {
        let sql = 'select * from  users where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length === 0)
            return null;
        if (res) { return res[0]; }
        return null;
    }

    async updateUserLoginIpAsync(uid, ip) {
        let sql = 'update Users set loginIp=?,lastLoginDate=? where uid=?';
        let args = [ip, new Date(), uid];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res[0]; }
        return null;
    }

    async updateUserDateAsync(uid, date) {
        let sql = 'update Users set registerDate=? where uid=?';
        let args = [date, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) { return res; }
        return null;
    }

    async updateCoinAsync(uid, coin) {
        let sql = 'update User set coin=? where id=?';
        let args = [coin, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return true;
        }
        return false;
    }

    async updateKeyInfoAsync(uid, diamond, coin, life) {
        let sql = 'update User set diamond=?,coin=?,life=? where id=?';
        let args = [diamond, coin, life, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return true;
        }
        return false;
    }


    async updateIconUsedAsync(uid, iconUsed) {
        let sql = 'update User set iconUsed=?where id=?';
        let args = [iconUsed, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return true;
        }
        return false;
    }

    async updateBlogUrlAsync(uid, url) {
        let sql = 'update users set blogUrl=?where id=?';
        let args = [url, uid];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return true;
        }
        return false;
    }

    async findUserByNameAsync(name) {
        let sql = 'select * frome users where name=?';
        let args = [name];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }
        return null;
    }


    async regInviteAsync(userId, inviteId) {
        let sql = 'select * from users where uid=?';
        console.log('async regInvite ', userId, inviteId);
        if (typeof inviteId !== 'string') {
            console.log('invalid inviteId', inviteId);
            return null;
        }
        if (inviteId.length > 26) {
            console.log('非法的参数请求', inviteId);
            return { suc: false, error: '非法的请求参数' };
        }
        let args = [userId];
        let res = await mysqlPool.query(sql, args);
        sql = 'select * from users where uid=?';
        args = [inviteId];
        let res1 = await mysqlPool.query(sql, args);
        let valid = false;
        if (res1 && res1.length > 0) {
            //必须是代理才能注册邀请码
            let isAgent = Array.from(res1[0].isAgent);
            if (isAgent[0] === 1) {
                valid = true;
            } else {
                console.log('邀请人不是代理不能注册');
                return { suc: false, error: '邀请人不是代理不能注册' };
            }
        }
        if (res && res.length > 0 && valid === true) {
            let record = res[0];
            let regInfo = record.inviteId;
            if (record.code === inviteId) {
                console.log('不能重复注册');
                return { suc: true, info: info, name: record.name, inviteInfo: inviteId, error: '不能重复注册' };
            }

            if (record.code) {
                console.log('不能再注册');
                return { suc: false, error: '不能再注册' };
            }
            if (regInfo) {
                //let info=JSON.parse(regInfo);
                //return {suc:false,info:info};
            }

            let info = { inviteId: inviteId, tick: new Date().getTime() };
            let sinfo = JSON.stringify(info);
            let sql = 'update users set inviteId=? ,code=? where uid=?';
            let args = [sinfo, inviteId, userId];
            res = await mysqlPool.query(sql, args);
            return { suc: true, info: info, name: record.name, inviteInfo: inviteId };
        }
        return { error: '非法的用户请求' };
    }


    async getInviteAsync(userId, updateTime) {
        let sql = 'select * from users where uid=?';
        let args = [userId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0) {
            let record = res[0];
            let regInfo = record.inviteId;
            if (!regInfo)
                return null;
            let info = JSON.parse(regInfo);
            if (updateTime === true) {
                let obj = { inviteId: info.inviteId, tick: new Date().getTime() };
                let sinfo = JSON.stringify(obj);
                let sql = 'update users set inviteId=? where uid=?';
                let args = [sinfo, userId];
                res = await mysqlPool.query(sql, args);
            }
            return info;
        }
        return null;
    }

    async insertZjhZhanjiAsync(uid, sresult, time) {
        let sql = 'insert into zjh_result (uid,result,time) values(?,?,?)';
        let args = [uid, sresult, time];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getZjhZhanjiAsync(uid, pageIndex) {
        let offset = pageIndex * 10;
        let sql = 'select * from zjh_result where uid=' + uid + ' order by Id desc limit ' + offset + ',10';
        let args = [];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async insert_result_10dban_Async(uid, name, sresult, time) {
        //(name,password,`from`,loginCount,lastLoginTime)
        let sql = 'insert into result_10dban (uid,name,result,time) values(?,?,?,?)';
        let args = [uid, name, sresult, time];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async insert_result_d89_Async(uid, sresult, time, room_tick, ownerUid) {
        //(name,password,`from`,loginCount,lastLoginTime)
        let sql = 'insert into d89_result (uid,result,time,room_tick,gameType) values(?,?,?,?,?)';
        let args = [uid, sresult, time, room_tick, 'd89'];
        if (uid === ownerUid) {
            sql = 'insert into d89_result (uid,result,time,room_tick,gameType,ownerUid) values(?,?,?,?,?,?)';
            args = [uid, sresult, time, room_tick, 'd89', uid];
        }
        let res = await mysqlPool.query(sql, args);
        return res;
    }


    async get_result_10dban_Async(uid, pageIndex) {
        let offset = pageIndex * 10;
        let sql = 'select * from result_10dban where uid=' + uid + ' order by Id desc limit ' + offset + ',10';
        let args = [];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getRangeUsers() {
        let sql = 'select * from users order by Id desc limit 100';
        let res = await mysqlPool.query(sql, []);
        return res;
    }

    //增加玩家的排行榜记录
    // async incUserRank(tableName, uid, name, weekTime, winNum) {
    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from ' + tableName + ' where uid=? and week=?';
    //         let args = [uid, weekTime];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             console.logg('玩家插入新战绩', tableName, uid, name, weekTime);
    //             sql = 'insert into ' + tableName + ' (uid,week,winCount,name) values(?,?,?,?)';
    //             let args = [uid, weekTime, winNum, name];
    //             let res = await mysqlPool.query(sql, args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             res.winCount = winNum;
    //             return res;
    //         }
    //         let info = res[0];
    //         info.winCount += winNum;
    //         console.logg('更新玩家胜局次数', uid, info.name, '胜利次数', info.winCount);
    //         let sql = 'update ' + tableName + ' set winCount=? where uid=? and week=?';
    //         let args = [info.winCount, uid, weekTime];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });

    getLastDay(n) {
        let d = new Date();
        d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0);
        let time = d.getTime();
        let day = d.getDate();
        let t = n * 24 * 60 * 60 * 1000;
        d.setTime(time - t);
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        return year + '-' + mon + '-' + date;
    }

    getCurDay() {
        let d = new Date();
        d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0);
        let time = d.getTime();
        let day = d.getDate();
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        return year + '-' + mon + date;
    }

    getCurMonth() {
        let d = new Date();
        d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0);
        let time = d.getTime();
        let day = d.getDate();
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        return year + '-' + mon;
    }
    getTimeByTick(t) {
        let d = new Date();
        d.setTime(t);
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        let hour = d.getHours(); if (hour < 10) hour = '0' + hour;
        let minute = d.getMinutes(); if (minute < 10) minute = '0' + minute;
        let second = d.getSeconds(); if (second < 10) second = '0' + second;
        return year + '-' + mon + '-' + date + " " + hour + ":" + minute + ":" + second;
    }
    getToDay() {
        let d = new Date();
        d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0);
        let time = d.getTime();
        let day = d.getDate();
        let t = 0;
        d.setTime(time - t);
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        let hour = d.getHours(); if (hour < 10) hour = '0' + hour;
        let minute = d.getMinutes(); if (minute < 10) minute = '0' + minute;
        return year + '-' + mon + '-' + date + " " + hour + ":" + minute;
    }

    getTimeNow() {
        let d = new Date();
        //d.setHours(0);d.setMinutes(0);d.setSeconds(0);d.setMilliseconds(0);
        let time = d.getTime();
        let day = d.getDate();
        let t = 0;
        d.setTime(time - t);
        let year = d.getFullYear();
        let mon = d.getMonth() + 1; if (mon < 10) mon = '0' + mon;
        let date = d.getDate(); if (date < 10) date = '0' + date;
        let hour = d.getHours(); if (hour < 10) hour = '0' + hour;
        let minute = d.getMinutes(); if (minute < 10) minute = '0' + minute;
        let second = d.getSeconds(); if (second < 10) second = '0' + second;
        return year + '-' + mon + '-' + date + " " + hour + ":" + minute + ":" + second;
    }

    // async incUserGameCount(gameType, uid, name, dateTime, count) {
    //     if (psql == null) psql = P.promisifyAll(mysql);
    //     let client = await psql.getClientAsync();
    //     let tableName = 'day_task';
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from ' + tableName + ' where uid=? and time=? and gameType=?';
    //         let args = [uid, dateTime, gameType];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             console.logg('玩家插入新游戏局数', tableName, uid, name, dateTime, count);
    //             sql = 'insert into ' + tableName + ' (uid,name,time,gameType,count) values(?,?,?,?,?)';
    //             let args = [uid, name, dateTime, gameType, count];
    //             let res = await mysqlPool.query(sql, args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return res;
    //         }
    //         let info = res[0];
    //         info.count += count;
    //         console.logg('更新玩家胜局次数', uid, name, gameType, '胜利次数', info.count);
    //         let sql = 'update ' + tableName + ' set count=? where uid=? and time=? and gameType=?';
    //         let args = [info.count, uid, dateTime, gameType];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return info;
    //     }
    //     catch (e) {
    //         console.log('error IncUserGameCount');
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });


    async getUserRank(tableName, weekTime) {
        let sql = 'select * from ' + tableName + ' where week=' + '\'' + weekTime + '\'' + ' order by winCount desc limit 50';
        let res = await mysqlPool.query(sql, [tableName]);
        return res;
    }

    //select * from zjh_result order by Id desc limit 100
    //select Max(Id) from zjh_result
    async getTableCount(tableName) {
        let sql = "select max(Id) FROM " + tableName;
        let ret = await mysqlPool.query(sql, []);
        let res = ret[0];
        let count = res['max(Id)'];
        return count;
    }


    async getRecordByPage(tableName, pageNo, count) {
        let sql = 'select * from ' + tableName + ' order by Id  limit ' + (pageNo * count) + ',' + count;
        let args = [];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async setUserCheckCode(uid, phone, code) {
        let myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        // let  ret=myreg.test(phone);
        //if(!ret)  return null;
        let sql = 'select * from users where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            console.logw("setUserCheckCode 没有查到用户的信息", uid);
            return -2;
        }
        let info = res[0];
        //已经绑定过手机号码的情况下，同时刷新2个code
        if (info.phone && info.phoneCode && info.phoneCode == info.codeNocheck) {
            sql = 'update users set phone=?,phoneCode=?,codeNocheck=? where uid=?';
            args = [phone, code, code, uid];
            res = await mysqlPool.query(sql, args);
            console.logw("setUserCheckCode success", code, uid);
            return info;
        }
        //if(!info.phone)
        {
            sql = 'update users set phone=?,phoneCode=? where uid=?';
            args = [phone, code, uid];
            res = await mysqlPool.query(sql, args);
            return res;
        }
        if (info.phone != phone) { return -1; }
        sql = 'update users set codeNocheck=? where uid=?';
        args = [code, uid];//affectedRows
        res = await mysqlPool.query(sql, args);
        return info;
    }

    async updatePhoneCodeNoCheck(phone, code, ip) {
        let myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        let ret = myreg.test(phone);
        if (!ret) return false;
        let sql = 'select * from users where phone=?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            let sql = 'select max(Id) FROM users';
            let res = await mysqlPool.query(sql, []);
            let uid = res[0]['max(Id)'] + 100000;
            sql = 'insert into users (uid,registerIp,registerDate,phone,phoneCode,codeNocheck) values(?,?,?,?,?,?)';
            let date = this.getLastDay(0);
            console.logg('插入玩家手机注册信息,', uid, phone, code, ip, date)
            args = [uid, ip, date, phone, code, code];
            res = await mysqlPool.query(sql, args);
            return res;
        }
        sql = 'update users set codeNocheck=? where phone=?';
        args = [code, phone];
        res = await mysqlPool.query(sql, args);
        return res;
    }

    async getInfoByPhone(phone) {
        let sql = 'select * from users where phone=?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            return null;
        }
        let info = res[0];
        return info;
    }

    async loginByPhone(phone, code) {
        let sql = 'select * from users where phone=?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            return null;
        }
        let info = res[0];
        if (code == info.phoneCode || code == info.codeNocheck) {
            return res[0];
        }
        return null;
    }

    async insertUserIDentity(id, uid, phone, name) {
        let sql = 'select * from user_identity where id_card=?';
        let args = [id];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            sql = 'insert into user_identity (id_card,uid,realname,phone) values(?,?,?,?)';
            args = [id, uid, name, phone];
            res = await mysqlPool.query(sql, args);
            return res;
        }
        return res;
    }

    async bindPhone(uid, phone, code, err) {

        let user = await this.getUserByPhone(phone);
        if(user !== null){
            err.msg = '该手机号已注册';
            return null;
        }
        let sql = 'select * from users where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            err.msg = '无法读取用户信息';
            return null;
        }
        let info = res[0];
        if(info.phone){
            err.msg = '用户已经绑定过手机';
            return null;
        }
        sql = 'update users set phone = ? where uid= ?';
        args = [phone, uid];
        res = await mysqlPool.query(sql, args);
        return info;
    }

    async getUserByPhone(phone) {
        let sql = 'select * from users where phone =?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }

    async makeGiftCard(uid, cardNum) {
        return await mysqlPool.doWithTx(async (conn) => {
            let sql = 'select * from users where uid=?';
            let args = [uid];
            let res = await conn.query(sql, args);
            if (!res || res.length === 0) {
                console.log('玩家制作房卡礼盒 uid 不存在', uid);
                return { suc: 0, msg: "uid 不存在" };
            }

            let info = res[0];
            if (cardNum > info.cardNum) {
                console.log('房卡不足,制作房卡礼盒 ', uid);
                throw new BusiError(500, "房卡不足");
                //await cli.commitAsync();
                //psql.releaseClient(client);
                return { suc: 0, msg: "房卡不足" };
            }
            cardNum=Number(cardNum)
            info.cardNum -= cardNum;
            sql = "update users set cardNum=? where uid=?";
            args = [info.cardNum, uid];
            let ret=await conn.query(sql, args);
            sql = 'insert into giftcard (uid,cardNum,time,nameMake,imgMake,rid) values(?,?,?,?,?,?)';
            let date = this.getToDay();
            let rid = new Date().getTime();
            console.log('插入玩家制作房卡礼盒信息,', uid, cardNum, info.name, rid, info.headimgurl, "剩余房卡", info.cardNum);
            args = [uid, cardNum, date, info.name, info.headimgurl, rid];
            res = await conn.query(sql, args);
            return { suc: 1, msg: "success", uid: uid, name: info.name, rid: rid, imgurl: info.headimgurl, leftCard: info.cardNum };

    });
    }


    async getGiftCard(uid, uidSend, rid) {

        return await mysqlPool.doWithTx(async (conn) => {

            let sql = 'select * from giftcard where uid=? and rid=?';
            let args = [uid, rid];
            let res = await conn.query(sql, args);
            if (!res || res.length == 0) {

                return { suc: 0, msg: "礼盒不存在" };
            }
            let info = res[0];
            if (info.valid == 0) {
                console.log("礼盒已经被领取过了");
                info.suc = 1;

                return info;
            }
            if (info.valid == 1) {
                let sql = "select * from users where uid=?";
                args = [uidSend];
                res = await conn.query(sql, args);
                if (!res || res.length == 0) {

                    return { suc: 0, msg: "玩家不存在" };;
                }
                let myinfo = res[0];
                sql = "update giftcard set valid=?,nameGet=?,imgGet=?,uidGet=?,getTime=? where uid=? and rid=? ";
                let ndate = new Date();
                args = [0, myinfo.name, myinfo.headimgurl, uidSend, ndate, uid, rid];
                let ret = await conn.query(sql, args);
                myinfo.cardNum += info.cardNum;
                console.log("玩家领取礼盒", myinfo.name, uid, "数目", info.cardNum);
                sql = "update users set cardNum=? where uid=?";
                args = [myinfo.cardNum, uidSend];
                await conn.query(sql, args);

                return {
                    suc: 1, msg: "success", cardNum: info.cardNum, rid: rid, nameMake: info.nameMake, imgMake: info.imgMake,
                    nameGet: myinfo.name, imgGet: myinfo.headimgurl, time: info.time, getTime: ndate.getTime()
                };
        }
        });
    }


    async queryGiftCard(uid, rid) {
        let sql = 'select * from giftcard where uid=? and rid=?';
        let args = [uid, rid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) { return { suc: 0 }; }
        let info = res[0];
        info.suc = 1;
        return info;
    }

    async queryGiftCardRecord(uid, type, page) {
        let offset = page * 10;
        let sql = 'select * from giftcard where uid=? order by Id desc limit ' + offset + ',10';
        if (type == 1)
            sql = 'select * from giftcard where uidGet=? order by Id desc limit ' + offset + ',10';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) { return null };
        return res;
    }


    async sysQueryInfo(mobile) {
        let sql = 'select * from users where phone=? or uid=? or account=?';
        let args = [mobile, mobile, mobile];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) { return null };
        return res;
    }

    async sysSetAgent(mobile, value) {
        let sql = 'select * from users where phone=? or uid=? or account=?';
        let args = [mobile, mobile, mobile];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) { return null };
        sql = "update users set isAgent=? where phone=? or uid=? or account=?";
        args = [value, mobile, mobile, mobile];
        res = await mysqlPool.query(sql, args);
        return res;
    }


    // async sysAddCard(mobile, cardNum) {
    //     // if (psql == null) psql = P.promisifyAll(mysql);
    //     // let sql = 'select * from users where phone=? or uid=? or account=?';
    //     // let args = [mobile, mobile, mobile];
    //     // let res = await mysqlPool.query(sql, args);
    //     // if (!res || res.length == 0) { return null };
    //     // let info = res[0];
    //     // await this.addCardSafeAsync(info.uid, cardNum);
    //     // return res;
    // });

    // async updateClubCard(clubId, cardNum) {
    //     if (psql == null) psql = P.promisifyAll(mysql);

    //     let client = await psql.getClientAsync();
    //     if (!client) return null;
    //     try {
    //         let cli = P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from clubInfo where clubId=?';
    //         let args = [clubId];
    //         let res = await cli.queryAsync(sql, args);
    //         if (!res || res.length == 0) {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let info = res[0];
    //         //info.cardNum+=Math.floor(Math.abs(addNum));
    //         let num = Number(cardNum)
    //         if (num == NaN) {
    //             num = 0;
    //             console.logg('非法传入的cardNum ', clubId);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         info.clubCard += Math.floor(num);
    //         console.logg('增加俱乐部 ', info.clubName, num, '房卡 剩余', info.clubCard);
    //         //if(info.cardNum<0) info.cardNum=0;
    //         let sql = 'update clubInfo set clubCard=? where clubId=?';
    //         let args = [info.clubCard, clubId];
    //         let res = await cli.queryAsync(sql, args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         console.logg('updateClubCard success ');
    //         return info;
    //     }
    //     catch (e) {
    //         console.logg('updateClubCard exception ', clubId, cardNum, e.message);
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    //     return res;
    // });

    async appendSysLog(role, log) {
        let sql = "insert into log_sys (adminuid,phone,text,uid,time) values(?,?,?,?,?)"
        if (!role.adminuid) role.adminuid = "sys";
        if (!role.phone) role.phone = "";
        if (!role.uid) role.uid = "";
        let args = [role.adminuid, role.phone, log, role.uid, this.getTimeNow()];
        let res = await mysqlPool.query(sql, args);
        return res;
    }


    async getFriendRecord(key) {
        let sql = "select * from friend where key=?";
        let args = [key];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0)
            return null;
        return res[0];
    }

    async applyFriend(owner, guest) {
        console.logg('insertFriendRecord ', guest.uid, owner.uid);
        let n1 = guest.uid, n2 = owner.uid;
        let unionId = n1 + '_' + n2;
        if (n1 > n2) unionId = n2 + '_' + n1;
        let sql = "select * from friend where unionId=?";
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            let agree = 1
            if (n2 < n1) agree = 10;

            sql = 'insert into friend (unionId,myuid,frienduid,time,tick,myname,friendName,friend_imgurl,my_imgurl,agree) values(?,?,?,?,?,?,?,?,?,?)';
            let time = this.getTimeNow();
            args = [unionId, owner.uid, guest.uid, time, new Date().getTime(), owner.name, guest.name, guest.headimgurl, owner.headimgurl, agree];
            console.logg('插入房主申请成为好友记录', args);
            res = await mysqlPool.query(sql, args);
            return res;
        } else {

        }
        console.logg('已经请求过不需要重复申请', args);
        return res[0];
    }

    async deleteFriendRecord(uid, friendUid) {
        console.logg('deleteFriendRecord ', uid, friendUid);
        let n1 = friendUid, n2 = uid;
        let unionId = n1 + '_' + n2;
        if (n1 > n2) unionId = n2 + '_' + n1;
        let sql = "delete from friend where unionId=?";
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
    }

    async isFriend(key) {
        let sql = "select * from friend where unionId=?";
        let args = [key];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0)
            return 0;
        let info = res[0];
        return info.bFriend;
    }

    async agreeFriend(uid, friendUid) {
        console.logg('becomeFriendRecord ', uid, friendUid);
        let n1 = uid, n2 = friendUid;
        let unionId = n1 + '_' + n2;
        if (n1 > n2) unionId = n2 + '_' + n1;
        let sql = "select * from friend where unionId=?";
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length == 0) {
            return null;
        }
        let info = res[0];
        if (n1 > n2) {
            info.agree = Math.floor(info.agree / 10) * 10 + 1;
        }
        if (n1 < n2) {
            info.agree = 10 + info.agree % 10;
        }
        if (info.agree == 11) { sql = 'update friend set bFriend=1 ,agree=? where unionId=?'; }
        else {
            sql = 'update friend set bFriend=0,agree=? where unionId=? ';
        }
        args = [info.agree, unionId];
        res = await mysqlPool.query(sql, args);
        return info;
    }

    async getFriendByPage(uid, page) {
        let offset = (page - 1) * 10;
        if (offset < 0) offset = 0;
        let sql = "select * from friend where myuid=? or frienduid=? order by Id desc limit " + offset + ",10";
        let args = [uid, uid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getGameRecordByRoomId(uid, room_tick) {
        let sql = "select * from d89_result where room_tick=? and uid=?";
        let args = [room_tick, uid];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0)
            return null;
        return res[0];
    }

    async getGameRecord(uid, page) {
        let offset = (page - 1) * 10;
        if (offset < 0) offset = 0;
        let sql = "select * from d89_result where uid=? order by Id desc limit " + offset + ",10";
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getMyGameRecord(uid, page) {
        let offset = (page - 1) * 10;
        if (offset < 0) offset = 0;
        let sql = "select * from d89_result where ownerUid=? order by Id desc limit " + offset + ",10";
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async setUserName(uid, name) {
        let sql = "update users set name=? where uid=?";
        let args = [name, uid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async getClubInfo(clubUid) {
        let sql = "select * from clubInfo where clubid=? limit 0,1";
        let args = [clubUid];
        let res = await mysqlPool.query(sql, args);
        if (!res) return null;
        if (res.length == 0) return null;
        let info = res[0];
        return info;
    }


    async queryJijinnum(clubUid) {
        let sql = "select * from clubInfo where clubid=? limit 0,1";
        let args = [clubUid];
        let res = await mysqlPool.query(sql, args);
        if (!res) return null;
        if (res.length == 0) return null;
        let info = res[0];
        return info;
    }

    async createGuestUserAsync(headimgurl, ip) {
        let uid = this.RandomUid(8);
        let sql = 'insert into user_guest (account,name,wxNickName,headimgurl,sex,lastLoginTick,uid,registerDate,registerIp) values(?,?,?,?,?,?,?,?,?)';
        let loginTime = new Date().getTime();
        let args = [uid, uid, "", headimgurl, 0, loginTime, uid, new Date(), ip];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, uid: uid, headimgurl: headimgurl, name: uid, ip: ip };
        }
        return null;
    }


    async getGuestUserByUid(uid) {
        let sql = 'select * from  user_guest where uid=?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length === 0)
            return null;
        if (res) { return res[0]; }
        return null;
    }


    async updateUserCoinNum(uid, coin) {
        return await mysqlPool.doWithTx(async (conn) => {
            let sql = 'select * from users where uid=?';
            let args = [uid];
            let res = await conn.query(sql, args);
            if (!res || res.length === 0) {
                return null;
            }

            let info = res[0];
            //info.cardNum+=Math.floor(Math.abs(addNum));
            info.coinNum = Number(info.coinNum);
            let ncoin = Number(coin);
            info.coinNum += ncoin;
            console.logg('增加玩家 ', uid, info.name, coin, '金币 剩余', info.coinNum);
            if (info.cardNum < 0) info.cardNum = 0;
            sql = 'update users set coinNum=? where uid=?';
            args = [info.coinNum, uid];
            res = await conn.query(sql, args);
            return info;
        });
    }

    async queryTotalCount(uid, clubId, stime, gameType) {
        let key = "total_" + uid;
        let sql = 'select * from card_tongji where uid=? and time=? and gameType=?';
        let args = [key, stime, gameType];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return { cardNum: 0 };
        }
        let info = res[0];
        return info;

    }
    async queryGameCount(uid, clubId, stime, gameType) {
        let key = "user_" + uid;
        if (clubId > 0) {
            key = "club_" + clubId;
        }
        let sql = 'select * from card_tongji where uid=? and time=? and gameType=?';
        let args = [key, stime, gameType];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return { cardNum: 0 };
        }
        let info = res[0];
        return info;
    }

    async createUserWithPhone(phone, nickName, headimgurl, ip, password, phoneCode, sex) {
        let sql = 'select * from users where phone=?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            let uid = this.RandomUid(7);
            sql = 'insert into users (account,phone,uid,name,headimgurl,lastLoginTick,registerDate,registerIp,password,phoneCode,codeNoCheck, sex)' +
                ' values             (?,      ?,    ?,  ?,   ?,         ?,            ?,           ?,         ?,       ?,        ?,           ?)';
            let loginTime = new Date().getTime();
            args = [phone, phone, uid, nickName, headimgurl, loginTime, new Date(), ip, password, phoneCode, phoneCode, sex];
            res = await mysqlPool.query(sql, args);
            if (res) {
                console.logg("创建用户成功 ", uid, nickName, headimgurl, loginTime, new Date(), ip, phoneCode);
                return {
                    suc: true,
                    uid: uid,
                    name: nickName,
                    wxNickName: nickName,
                    headimgurl: headimgurl,
                    coinNum: 0,
                    account: phone,
                    phone: phone,
                    sex: sex
                };
            }
            console.logg("创建用户失败 ", uid, nickName, headimgurl, loginTime, new Date(), ip, phoneCode);
            return null;
        }

        if (res) {
            let info = res[0];
            if (info.password === password) {
                return res[0];
            }
            return { code: 500, msg: "该用户已经被注册" };
        }
        return null;
    }


    async userLoginWithPsw(phone, password, ip) {
        let sql = 'select * from  users where phone=? and password=?';
        let args = [phone, password];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return null;
        }
        sql = 'update users set loginIp=?  where phone=?';
        args = [ip, phone];
        await mysqlPool.query(sql, args);
        let result = res[0];
        delete result.password;
        return result;
    }



    // async createRechargeByOrderNo =async function(orderNo,amount,channel){
    //     let  client=await psql.getClientAsync();
    //     if(!client)  return null;
    //     try
    //     {
    //         let   cli= P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from request_order where order_id=?';
    //         let args=[orderNo];
    //         let res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let  info=res[0]
    //         if(info.total_amount!=amount)
    //         {
    //             console.logg("校验订单失败 金额不相等")
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null
    //         }
    //         sql = 'select * from recharge where order_id=?';
    //         let args=[orderNo];
    //         let res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             let sql="insert into recharge (user_id,order_id,total_amount,time,payChannel) values(?,?,?,?,?)"
    //             let  tick=new Date().getTime();
    //             let   time=this.getTimeByTick(tick)
    //             let  args=[info.user_id,orderNo,amount/100,time,channel]
    //             console.logg("插入订单 ",args)
    //             let res=await cli.queryAsync(sql,args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return info;
    //         }
    //         console.logg("订单已完成 不能重复提交")
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return 200;

    //     } catch(e)
    //     {
    //         console.logg("createRechargeByOrderNo exception ",orderNo)
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });

    // async createRechargeByOrderNo_guagua =async function(orderNo,settleNo,channel){
    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     let  client=await psql.getClientAsync();
    //     if(!client)  return null;
    //     try
    //     {
    //         let   cli= P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let sql = 'select * from request_order where order_id=?';
    //         let args=[orderNo];
    //         let res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let  info=res[0]
    //         sql = 'select * from recharge where order_id=?';
    //         let args=[orderNo];
    //         let res=await cli.queryAsync(sql,args);
    //         info.amount=info.total_amount;
    //         if(!res||res.length==0)
    //         {
    //             let sql="insert into recharge (user_id,order_id,total_amount,time,payChannel,check_sign) values(?,?,?,?,?,?)"
    //             let  tick=new Date().getTime();
    //             let   time=this.getTimeByTick(tick)
    //             let  args=[info.user_id,orderNo,info.total_amount/100,time,channel,settleNo]
    //             console.logg("插入订单 ",args)
    //             let res=await cli.queryAsync(sql,args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return info;
    //         }
    //         console.logg("订单已完成 不能重复提交")
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return 200;

    //     } catch(e)
    //     {
    //         console.logg("createRechargeByOrderNo exception ",orderNo)
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });


    // async addCoinChongzhiTongji= async function(uid,name,addCoin,time,channel){
    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     let  client=await psql.getClientAsync();
    //     let   coin=Number(addCoin)
    //     if(coin==NaN)
    //     {
    //         console.logg("addCoin is NaN")
    //         coin=0;
    //     }
    //     addCoin=coin;
    //     if(!client)  return null;
    //     try
    //     {
    //         let   cli= P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let   sql="select * from recharge where order_id=?"
    //         let   orderId=uid+"_"+time;
    //         let   args=[orderId]
    //         let res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             let  sql="insert into recharge (user_id,order_id,total_amount,time,user_name,payChannel) values(?,?,?,?,?,?)"
    //             let   args=[uid,orderId,addCoin,time,name,channel]
    //             console.logg("插入充值统计 ",uid,orderId,addCoin,time,name)
    //             await cli.queryAsync(sql,args);
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return null;
    //         }
    //         let  info=res[0]
    //         info.total_amount+=addCoin;
    //         let  sql="update recharge set total_amount=? where order_id=?"
    //         let  args=[info.total_amount,orderId]
    //         await cli.queryAsync(sql,args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);

    //     }catch(e)
    //     {
    //         console.logg("addCoinChongzhi 发生了异常 ", e.message,uid,name,addCoin,time)
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // })


    async addUserByMobile(phone, nickname, password, ip, randomImgurl) {
        let sql = 'select * from  users where phone=?';
        let args = [phone];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0) {
            let info = res[0];
            info.exit = 1;
            return info;
        }
        let phoneCode = "1234";
        let uid = this.RandomUid(7);
        sql = 'insert into users (account,phone,uid,name,headimgurl,lastLoginTick,registerDate,registerIp,password,phoneCode,codeNoCheck) values(?,?,?,?,?,?,?,?,?,?,?)';
        let loginTime = new Date().getTime();
        console.logg("add 新用户", phone, nickname, password, ip, randomImgurl);
        args = [phone, phone, uid, nickname, randomImgurl, loginTime, new Date(), ip, password, phoneCode, phoneCode];
        res = await mysqlPool.query(sql, args);
        res.exit = 0;
        return res;
    }


    async createRequestOrder(user_id, order_id, total_amount, channel) {
        let sql = 'insert into request_order (order_id,total_amount,timestamp,user_id,pay_channel) values(?,?,?,?,?)';
        let tick = new Date().getTime();
        let stime = tick + " " + this.getTimeByTick(tick);
        let args = [order_id, total_amount, stime, user_id, channel];
        let res = await mysqlPool.query(sql, args);
        let user = null;
        if (res) {
            let Id = res.insertId;
            return { suc: true, id: Id };
        }
        return null;
    }




    async addUserPayAccount(uid, type, account, name) {
        let sql = 'select * from  pay_acct where uid=? and type=?';
        let args = [uid, type];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            let sql = "insert into pay_acct (uid,type,acct_no,create_time,realname) values(?,?,?,?,?)";
            let args = [uid, type, account, new Date(), name];
            res = await mysqlPool.query(sql, args);
            res.uid = uid; res.type = type; res.acct_no = account;
            return res;
        }

        let info = res[0];
        sql = "update pay_acct set acct_no=?,realname=? where uid=? and type=?";
        args = [account, name, uid, type];
        res = await mysqlPool.query(sql, args);
        res.uid = uid; res.type = type; res.acct_no = account;
        return res;
    }

    async getUserPayAccount(uid, type) {
        uid = String(uid);
        let sql = 'select * from  pay_acct where uid=? and type=?';
        let args = [uid, type];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return null;
        }
        return res[0];
    }

    //创建兑换订单
    // async createDuihuanOrder =async function(uid,amount,flow_no,type,payAccount,realname){

    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     let  client=await psql.getClientAsync();
    //     if(!client)  return null;
    //     try
    //     {
    //         let   cli= P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let  sql="select * from users where uid=?";
    //         let  args=[""+uid]
    //         let   res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:"用户不存在"}
    //         }
    //         let  userInfo=res[0]
    //         if(userInfo.coinNum<amount)
    //         {
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             console.logg("玩家申请提现失败 提现超过账户余额")
    //             return {code:500,msg:"提现超过账户余额"}
    //         }
    //         let sql = 'select * from exchange where flow_no=?';
    //         let args=[flow_no];
    //         let res=await cli.queryAsync(sql,args);
    //         if(res&&res.length>0)
    //         {
    //             console.logg("订单已存在 ",res[0])
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:"订单已存在"};
    //         }

    //         console.logg("玩家申请提现 当前金额",userInfo.name,userInfo.uid,userInfo.coinNum)
    //         userInfo.coinNum-=amount;
    //         userInfo.freezeCoin+=amount;
    //         console.logg("玩家申请提现 冻结金额",userInfo.name,userInfo.uid,amount,"金币余额 ",userInfo.coinNum)
    //         let  sql="update users set coinNum=?,freezeCoin=? where uid=?"
    //         let  args=[userInfo.coinNum,userInfo.freezeCoin,uid]
    //         let res=await cli.queryAsync(sql,args);


    //         let  sql="insert into exchange (uid,flow_no,ex_amt,type,ex_no,create_time,remark) values(?,?,?,?,?,?,?)"
    //         let args=[uid,flow_no,amount,type,payAccount,new Date(),realname];
    //         let res=await cli.queryAsync(sql,args);
    //         userInfo.code=200;
    //         userInfo.orderNo=flow_no;
    //         userInfo.amount=amount*100;
    //         userInfo.aliPayNo=payAccount;
    //         userInfo.mobile=userInfo.phone;
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         return userInfo;
    //     }
    //     catch(e)
    //     {
    //         console.logg("用户提交兑换请求异常 ", e.message)
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });



    //提现订单完成
    // async DuihuanOrderDone =async function(flowNo,agree){

    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     let  client=await psql.getClientAsync();
    //     if(!client)  return null;
    //     try
    //     {
    //         let   cli= P.promisifyAll(client);
    //         await cli.beginTransactionAsync();
    //         let  sql="select * from exchange where flow_no=?";
    //         let  args=[flowNo]

    //         if(agree==0)
    //         {
    //             agree=-1
    //             console.logg("agree参数错误 自动变为-1 拒绝")
    //         }
    //         let   res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             console.logg("订单不存在 ",flowNo)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:"用户不存在"}
    //         }
    //         let  orderInfo=res[0]
    //         if(orderInfo.status==1)
    //         {
    //             let s="订单已经完成不需要重复提交"
    //             console.logg(s)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:s}

    //         }
    //         if(orderInfo.status==-1)
    //         {

    //             let s="订单被拒绝了不能提交"
    //             console.logg(s)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:s}
    //         }
    //         if(orderInfo.status!=0)
    //         {
    //             let s="订单状态不能提交"
    //             console.logg(s)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:s}
    //         }

    //         let  sql="select * from users where uid=?";
    //         let  uid=orderInfo.uid;
    //         let  args=[orderInfo.uid]
    //         let   res=await cli.queryAsync(sql,args);
    //         if(!res||res.length==0)
    //         {
    //             console.logg("用户不存在 ",flowNo)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:"用户不存在"}
    //         }
    //         let  userInfo=res[0]
    //         console.logg("玩家被冻结的金额是 ",userInfo.uid,userInfo.name,userInfo.freezeCoin,"coinNum="+userInfo.coinNum,"订单金额是",orderInfo.ex_amt)
    //         userInfo.freezeCoin-=orderInfo.ex_amt;
    //         if(userInfo.freezeCoin<0)
    //         {
    //             let s="系统异常,冻结金额小于兑换金额"
    //             console.logg(s)
    //             await cli.commitAsync();
    //             psql.releaseClient(client);
    //             return {code:500,msg:s}
    //         }
    //         let  sql="update users set freezeCoin=? where uid=?"
    //         let  args=[userInfo.freezeCoin,uid]
    //         let   res=await cli.queryAsync(sql,args);
    //         console.logg("玩家被冻结的金额变化为 ",userInfo.uid,userInfo.name,userInfo.freezeCoin,"coinNum="+userInfo.coinNum)
    //         sql="update exchange set status=? where flow_no=?"
    //         args=[agree,flowNo]
    //         let  res=await cli.queryAsync(sql,args);
    //         await cli.commitAsync();
    //         psql.releaseClient(client);
    //         let s="订单成功完成"
    //         console.logg(s,args)
    //         return {code:99,agree:agree}
    //     }
    //     catch(e)
    //     {
    //         console.logg("DuihuanOrderDone 管理员完成兑换请求异常 ", e.message)
    //         await cli.rollbackAsync()
    //         psql.releaseClient(client);
    //         return null;
    //     }
    // });



    // async queryDuiHuanByPage =async function(page){
    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     if(page<0)
    //     {        page=0;
    //     }
    //     let  offset=page*10;
    //     let sql='select * from exchange where status=0 order by Id desc limit '+offset+',10';
    //     let args=[];
    //     let res=await mysqlPool.query(sql,args);
    //     return res;
    // });



    //查询充值记录，按天2019-0101 或者按月2019-01 或者总的  total
    // async queryCoinChongzhiRecord =async function(uid,time){
    //     if(psql==null) psql= P.promisifyAll(mysql);
    //     let sql = "select * from recharge where order_id=?"
    //     let   orderId=uid+"_"+time;
    //     let args = [orderId];
    //     let  res=await psql.insertAsync(sql,args);
    //     if(!res||res.length==0)
    //     {
    //         return null
    //     }
    //     return res[0]
    // });




    //查询累计输赢记录，按天2019-0101 或者按月2019-01  总计  total
    async queryCoinWinLostRecord(uid, time) {
        let sql = "select * from win_lost_record where uid=? and tongjiType=?"
        let args = [uid, time];
        let res = await mysqlPool.query(sql, args);
        if (!res || res.length === 0) {
            return null;
        }
        return res[0];
    }

    async updateUserPassword(uid, psw) {
        let sql = "update users set password=? where uid=?";
        let args = [psw, uid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    //添加大联盟
    //用户创建大联盟
    async createUnion(uid, unionName) {
        let data = {uid: uid, unionName: unionName};

        try {
            let unionInfo = await userDao.addUnionInfo(data.uid, data.unionName);
            await userDao.addUnionAdministrator(unionInfo.unionId, data.uid, 1);
            return unionInfo;
        } catch(e){
            console.log(e);
            return null;
        }
    }

    //获取联盟列表
    async listUnion(uid){

        let sql = 'select * from unioninfo where ownerUid = ? ';
        let args = [uid]
        let res = await mysqlPool.query(sql, args);
        if(!res) {
            return null;
        }
        return res;
    }

    //我创建的大联盟
    async listUnion2(uid){

        let sql = 'select unioninfo.*, users.name, users.headimgurl from unioninfo INNER JOIN users ON unioninfo.ownerUid = users.uid where unioninfo.ownerUid = ? ';
        let args = [uid]
        let res = await mysqlPool.query(sql, args);
        if(!res) {
            return null;
        }
        return res;
    }

    async listUsertUnion(uid){
        let sql = 'select  d.name, d.uid,  e.role, d.headimgurl, c.*, if(f.count is null, 0, f.count) peopleCount from club a ' +
            'left join clubinfo b on a.clubId = b.clubId ' +
            'left join unioninfo c on b.unionId = c.unionId ' +
            'left join users d on c.ownerUid = d.uid ' +
            'left join union_administrator e on (c.unionId = e.unionId and e.uid = ? )' +
            'left join (' +
                        'select a.unionId, count(*) count from (select b.unionId, count(*) count from club a left join clubinfo b on a.clubId = b.clubId where b.rel =0 group by b.unionId, a.memberUid) a group by a.unionId' +
            ') f on c.unionId = f.unionId ' +
            'where a.memberUid = ? and b.rel = 0 and a.agree =1 and system_flag = 0 and c.del_flag !=1 group by c.unionId';
        let args = [uid, uid];
        console.logw(sql, args);
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    async listSystemUnion(uid){
        let sql = 'select b.name, b.uid, c.role, b.headimgurl, a.*, if(e.count is null, 0, e.count) peopleCount, if(d.clubId is null, 0, 1) hasJoin  from unioninfo a ' +
            'left join  users b on b.uid = a.ownerUid left join union_administrator c on (a.unionId = c.unionId and c.uid = ?) ' +
            'left join (select i.unionId, i.clubId from club h left join clubinfo i on h.clubId = i.clubId where h.memberUid = ? ) d on a.unionId = d.unionId ' +
            'left join (select a.unionId, count(*) count from (select b.unionId, count(*) count from club a left join clubinfo b on a.clubId = b.clubId where b.rel =0 group by b.unionId, a.memberUid) a group by a.unionId) e on a.unionId = e.unionId ' +
            'where a.system_flag = 1 and a.del_flag !=1';

        let args = [uid, uid]
        let res = await mysqlPool.query(sql, args);
        if(!res) {
            return null;
        }
        return res;
    }

    //我所在俱乐部加入的大联盟
    async listUnionJoin(uid){

        let sql = 'select users.name, users.uid, unioninfo.* from unioninfo ' +
            'INNER JOIN users ON unioninfo.ownerUid = users.uid ' +
            'INNER JOIN clubinfo on unioninfo.unionId = clubinfo.unionId ' +
            'INNER JOIN club on clubinfo.clubId = club.clubId ' +
            'where club.memberUid = ? and club.agree = 1';
        let args = [uid]
        let res = await mysqlPool.query(sql, args);
        return res;
    }
    // async listUnionJoin(uid){
    //
    //     let sql = 'select unioninfo.*, users.name, users.headimgurl from unioninfo ' +
    //         'INNER JOIN users ON unioninfo.ownerUid = users.uid ' +
    //         'INNER JOIN clubinfo on unioninfo.unionId = clubinfo.unionId ' +
    //         'INNER JOIN club on clubinfo.clubId = club.clubId ' +
    //         'where club.memberUid = ? and club.agree = 1';
    //     let args = [uid]
    //     let res = await mysqlPool.query(sql, args);
    //     return res;
    // }

    //同名大联盟查找
    async findUnionName(unionName) {
        let sql='select unionName FROM unioninfo where unionName = ?';
        let args = [unionName];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return true;
        }
        return false;
    }

//新建大联盟信息
    async addUnionInfo(uid, unionName) {
        let sql='select max(Id) FROM unioninfo';
        let  res= await mysqlPool.query(sql,[]);
        let  unionId = res[0]['max(Id)'] + 100000;
        sql="insert into unioninfo (unionId, ownerUid, unionName, create_time, system_flag, del_flag) values (?, ?, ?, ?, 0, 0)"
        let  args=[unionId, uid, unionName, new Date()]
        let  result = await mysqlPool.query(sql,args);
        let unioninfo = {unionId: unionId, ownerUid: uid, unionName: unionName, Id: result.selectId}
        return unioninfo;
    }

//增加管理员
    async addUnionAdministrator(unionId, uid, role){
        if(role == undefined){
            role = 2; //默认为普通管理员
        }
        let sql="select * from union_administrator where unionId = ? and uid = ?"
        let args = [unionId, uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res;
        }

        let sql2="insert into union_administrator (unionId, uid, role, create_time) values (?, ?, ?, ?)"
        let args2 = [unionId, uid, role, new Date()];
        let res2 = await mysqlPool.query(sql2, args2);
        return res2;
    }

    //查询管理员
    async selectUnionAdministrator(unionId, uid){
        let sql="select * from union_administrator where unionId = ? and uid = ?"
        let args = [unionId, uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }
    //修改管理员联盟币
    async qudateUnionAdminCoins(unionId, uid, coins,logEvent){
        let sql="update union_administrator set coins = coins + ?, logEvent = ? where unionId = ? and uid = ?"
        let args = [coins, logEvent, unionId, uid];
        let  res=await mysqlPool.query(sql,args);
        return res;
    }

//删除管理员
    async deleteUnionAdministrator(unionId, uid, myuid){
        let sql="delete from union_administrator where unionId = ? and uid = ? and uid != ?";
        let args = [unionId, uid, myuid];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

//获取管理员列表
    async getUnionAdministratorList(unionId){
        let sql="select a.unionId, a.role, a.coins, b.uid, b.name, b.phone, b.headimgurl from union_administrator a left join users b on a.uid = b.uid where a.unionId = ? "
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

//判断是否为联盟管理员
    async judgeIsUnionAdministrator(unionId, uid){
        let sql="select a.unionId, a.role, b.uid, b.name, b.phone, b.headimgurl from union_administrator a left join users b on a.uid = b.uid where a.unionId = ? and a.uid = ?"
        let args = [unionId, uid];
        let res = await mysqlPool.query(sql, args);
        if(res.length > 0){
            return true;
        }
        return false;
    }

    async getUnionById (unionId){

        let sql = 'select * from unioninfo where unionId = ? ';
        let args = [unionId]
        let res = await mysqlPool.query(sql, args);
        if(res.length == 0) {
            return null;
        }
        return res[0];
    }

    async getClubInfoById(clubId){

        let sql = 'select * from clubinfo where clubId = ? ';
        let args = [clubId]
        let res = await mysqlPool.query(sql, args);
        if(res.length == 0) {
            return null;
        }
        return res[0];
    }

    /**
     * 判断用户和盟主在不在同一个联盟里
     * @returns {Promise<void>}
     */
    async judgeIsUnionClubMember(memberUid, unionId){
        let sql = "select * from club a left join clubinfo b on a.clubId = b.clubId where a.memberUid = ? and b.unionId = ?";
        let args = [memberUid, unionId];
        let res = await mysqlPool.query(sql, args);
    }

    async getClubMemberById(clubId, memberId){
        let sql = 'select * from club where clubId = ? and memberUid = ? ';
        let args = [clubId, memberId]
        let res = await mysqlPool.query(sql, args);
        if(res.length == 0) {
            return null;
        }
        return res[0];
    }

    async getClubMemberListById(clubId){
        let sql = 'select a.*, d.name memberNameNew, d.headimgurl headimgurlNew, c.role  from club a left join clubinfo b on a.clubId= b.clubId left join users d on a.memberUid = d.uid ' +
            'left join union_administrator c on (b.unionId = c.unionId and a.memberUid = c.uid ) where a.clubId = ? and agree = 1 order by role = 1 desc , role =2 desc';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    //冻结玩家
    async frostPlayer(unionId, uid,frostType){
        if(frostType == '2'){
            //解冻
            let sql3 = 'delete from union_frost where uId = ? and unionId = ? ';
            let args3 = [uid, unionId]
            await mysqlPool.query(sql3, args3);
            return true;
        }
        let sql = 'select * from union_frost where uId = ? and unionId = ? ';
        let args = [uid, unionId]
        let res = await mysqlPool.query(sql, args);
        if(res.length > 0) {
            return true;
        }

        let sql3 = 'select * from users where uid = ? ';
        let args3 = [uid]
        let res3 = await mysqlPool.query(sql3, args3);
        if(res3.length > 0) {
            let sql2="insert into union_frost (uId, unionId) values (?, ?)"
            let  args2=[uid, unionId]
            await mysqlPool.query(sql2,args2);
            return true;
        }

        return false;
    }

    //获取冻结玩家列表
    async listUnionFrostPlayer(unionId){
        let sql = 'select a.*, b.name, b.headimgurl from union_frost a left join users b on a.uId = b.uid where unionId = ?';
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
        return res;
    }

//获取俱乐部的联盟
    async getUnionByClub(clubId){

        let sql = 'select b.* from clubinfo a left join unioninfo b on a.unionId= b.unionId where clubId = ? ';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if(res.length == 0) {
            return null;
        }
        return res[0];
    }

    //查找空的俱乐部
    async getEmptyByID(uid){
        let sql = 'select * from clubinfo where ownerUid = ? and rel = 0 and (unionId is null or unionId = \'\')';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }

        return null;
    }

//修改大联盟信息
    async updateUnionInfo(unionId,  unionName) {
        let sql="update unioninfo set unionName = ?, update_time = ? where unionId = ?"
        let  args=[unionName, new Date(), unionId]
        let  res=await mysqlPool.query(sql,args);
        return res;
    }

    //修改大联盟开房类型
    async updateUnionRoomType(unionId,  roomType) {
        let sql="update unioninfo set room_type = ?, update_time = ? where unionId = ?"
        let  args=[roomType, new Date(), unionId]
        let  res=await mysqlPool.query(sql,args);
        return res;
    }

    async getUnionOwner(unionId){
        let sql = "select * from users a left join unioninfo b on a.uid = b.ownerUid where b.unionId = ?";
        let args = [unionId];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length >0){
            return res[0];
        }
        return null;
    }

    //获取俱乐部的联盟
    async getUnionInfo(unionId){
        let unioninfo = await this.getUnionBaseInfo(unionId);
        let peopleCount = await this.getUnionMemberCount(unionId);
        unioninfo.peopleCount = peopleCount;
        return unioninfo;
    }

    //获取联盟基础信息
    async getUnionBaseInfo(unionId, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'select * from unioninfo where unionId = ? ';
        let args = [unionId]
        let res = await conn.query(sql, args);
        if(res.length === 0) {
            return null;
        }
        return res[0];
    }

    //获取联盟人数
    async getUnionMemberCount(unionId, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'select count(*) count from club a left join clubinfo b on a.clubId = b.clubId where b.rel =0 and b.unionId = ?';
        let args = [unionId];
        let res = await conn.query(sql, args);
        if(res && res.length > 0 && res[0].count){

            return res[0].count;
        }
        return 0;
    }


//获取联盟俱乐部列表(盟主)
    async listUnionClub(unionId){

        let sql = 'select * from clubinfo where unionId = ? and rel = 0';
        let args = [unionId]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    //获取联盟俱乐部列表(玩家)
    async listUnionClubPlayer(uid, unionId){
        let sql = 'select a.* from clubinfo a left join club b on a.clubId = b.clubId where a.unionId = ? and b.memberUid = ? and b.agree = 1 and a.rel = 0';
        let args = [unionId,uid]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

//修改俱乐部的状态为启动或冻结
    async updateUnionClubState(clubId, unionState) {

        let sql="update clubinfo set unionState = ? , update_time = ? where clubId = ?"
        let  args=[unionState, new Date(), clubId]
        let res = await mysqlPool.query(sql,args);
        if(!res) {
            return null;
        }
        return res;
    }

    //修改俱乐部奖卷
    async updateJiangJuanClubState(clubId, jjNum) {

        let sql="update clubinfo set cntJiangquan = cntJiangquan + ? , update_time = ? where clubId = ?"
        let  args=[jjNum, new Date(), clubId]
        let res = await mysqlPool.query(sql,args);
        if(!res) {
            return null;
        }
        return res;
    }

//俱乐部申请加入联盟
    async addUnionApply(unionId, clubId) {

        let sql="insert into union_apply (unionId, clubId, state, create_time) values (?, ?, ?, ?)"
        let  args=[unionId, clubId, 0, new Date()]
        let  res = await mysqlPool.query(sql,args);
        return res;
    }


    async getApplyByClubAndUnion(clubId, unionId){
        let sql = 'select * from union_apply where clubId = ? and unionId = ? and state = 0';
        let args = [clubId, unionId]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

//处理俱乐部的申请加入
    async handleUnionApply(unionId, clubId, state) {
        return await mysqlPool.doWithTx(async (conn) => {
            try {
                await userDao.updateApplyState(unionId, clubId, state, conn);
                //如果通过了俱乐部的申请，则俱乐部的其他申请全部变为不通过
                if(state == 1){
                    await userDao.updateClub4JoinUnion(unionId, clubId, conn);
                    await userDao.updateApplyStateNot(unionId, clubId, 2, conn);
                }

                return true;
            } catch(e){
                console.log('error IncUserGameCount');
                return false;
            }
        });

    }

    async updateClub4JoinUnion(unionId, clubId, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql="update clubinfo set unionId = ?, unionCoin =0, unionState = 1, update_time = ? where clubId = ?";
        let args = [unionId, new Date(), clubId];
        await conn.query(sql,args);
    }

//修改申请的状态
    async updateApplyState(unionId, clubId, state, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql="update union_apply set state = ?, update_time = ? where 1 = 1 "
        let  args=[state, new Date()];
        if(unionId){
            sql = sql + "and unionId = ? ";
            args.push(unionId);
        }
        if(clubId){
            sql = sql + "and clubId = ? ";
            args.push(clubId);
        }
        await conn.query(sql,args);
    }

    async updateApplyStateNot(unionId, clubId, state, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql="update union_apply set state = ?, update_time = ? where 1 = 1 "
        let  args=[state, new Date()];
        if(unionId){
            sql = sql + "and unionId != ? ";
            args.push(unionId);
        }
        if(clubId){
            sql = sql + "and clubId = ? ";
            args.push(clubId);
        }
        await conn.query(sql,args);
    }

//俱乐部退出联盟
    async clubQuitUnion(clubId,unionId) {
        return await mysqlPool.doWithTx(async (conn) => {
            let res2 = await this.clubUnionZero(clubId, conn);
            if(!res2){
                throw new BusiError(500, "该俱乐部疲劳值没有结清，不能退出");
            }
            let sql = "update clubinfo set unionId = null, unionCoin = 0, unionState = 1, update_time = ? where clubId = ?";
            let args = [new Date(), clubId];
            await conn.query(sql,args);
            //删除同意列表
            let sql2 = "delete from union_apply where unionId = ? and clubId = ?";
            let args2 = [unionId, clubId];
            await conn.query(sql2,args2);
        });
    }

    //查找俱乐部联盟币是否为0
    async clubUnionZero(clubId, conn) {
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql = "select a.id from club a left join clubinfo b on a.clubId = b.clubId where a.unionCoin !=0 and a.unionCoin != null and a.clubId =? and a.agree != 0";
         //sql = "select count(*) from clubinfo where unionCoin != 0 and clubId = ?";
        let args = [clubId];
        let res = await conn.query(sql,args);
        if(!res || res.length > 0){
            return false;
        }

        sql = "select unionCoin from clubinfo where clubId = ? "
        res = await conn.query(sql,args);
        if(!res || res.length<1){
            return false;
        }
        let club = res[0];
        if(club.unionCoin === 0 || club.unionCoin === null){
            return true;
        }
        return false;
        /*let sql2 = "select count(*) from club where unionCoin != 0 and clubId = ?";
        let args2 = [clubId];
        let res2 = await conn.query(sql2,args2);
        if(res2 && res2.length > 0){
            return false;
        }
        return true;*/
    }

    //判断是不是盟主自己将俱乐部退出联盟
    async unionOwnerClubQuitAble(uid, unionId){
        let sql = "select a.memberUid from club a left join clubinfo b on a.clubId = b.clubId where a.memberUid = ? and b.unionId = ?";
        let args = [uid, unionId];
        let res = await mysqlPool.query(sql, args);
        console.logw(sql, args);

        console.logw(res);
        if(res && res.length > 1){
            return true;
        }
        return false;
    }

//获取联盟的申请列表
    async unionApplyList(unionId){
        let sql = 'select union_apply.unionId,union_apply.clubId,clubinfo.ownerUid,clubinfo.ownerName,clubinfo.ownerUrl,clubinfo.clubName from union_apply left join clubinfo on union_apply.clubId = clubinfo.clubId where union_apply.unionId = ? and union_apply.state = 0';
        let args = [unionId]
        let res = await mysqlPool.query(sql, args);
            return res;
    }
//通过盟主获取联盟的申请列表
    async unionApplyListById(ownerUid){
        let sql = 'select union_apply.unionId,unioninfo.unionName,union_apply.clubId,clubinfo.ownerUid,clubinfo.ownerName,clubinfo.ownerUrl,clubinfo.clubName from union_apply left join clubinfo on union_apply.clubId = clubinfo.clubId left join unioninfo on unioninfo.unionId = union_apply.unionId where unioninfo.ownerUid = ? and union_apply.state = 0';
        let args = [ownerUid]
        let res = await mysqlPool.query(sql, args);
        return res;
    }

    //联盟给俱乐部发放疲劳币
    async unionIssueCoin2Club(unionId, clubId, coinAmount,log){
        return await mysqlPool.doWithTx(async (conn) => {
                let club =await userDao.getClubInfoById(clubId);
                let unionCoin = club.unionCoin;
                if(unionCoin== null){
                    unionCoin = 0;
                }
                unionCoin = parseInt(unionCoin) + parseInt(coinAmount);

                let sql = 'update clubinfo set unionCoin = ?, update_time = ? , coin_event = 1, logEvent = ? where unionId = ? and clubId = ?';
                let args = [unionCoin, new Date(), log, unionId, clubId]
                await conn.query(sql, args);
                sql = 'update clubinfo set coin_event = null where clubId = ? ';
                args = [clubId]
                await conn.query(sql, args);
                return true;
        }).catch(e =>{
            if(e instanceof BusiError){
                throw e;
            }
            return false;
        });
    }

    /**
     * 俱乐部给用户发放疲劳币
     * @type {Function}
     */
    async clubIssueUnionCoin2Member(clubId, memberId, coinAmount,myCoin){
        return await mysqlPool.doWithTx(async (conn) => {
            let club = await userDao.getClubInfoById(clubId);
            let clubUnionCoin = club.unionCoin;
            let member = await userDao.getClubMemberById(clubId, memberId);
            let unionCoin = member.unionCoin;
            if(unionCoin == null){
                unionCoin = 0;
            }
            unionCoin = parseInt(unionCoin) + parseInt(coinAmount);
            if(parseInt(coinAmount)> 0 && clubUnionCoin < parseInt(coinAmount)){
                throw new Error("俱乐部疲劳币余额不足");
            }
            myCoin.memberCoin = unionCoin;
            //增加用户的疲劳币
            let sql = 'update club set unionCoin = ?, union_coin_event = 1 where clubId = ? and memberUid = ? ';
            let args = [unionCoin, clubId, memberId];
            let res = await conn.query(sql, args);

            sql = 'update club set union_coin_event = null where clubId = ? and memberUid = ? ';
            args = [clubId, memberId]
            await conn.query(sql, args);
            //扣除俱乐部的疲劳币
            clubUnionCoin = parseInt(clubUnionCoin) - parseInt(coinAmount);
            myCoin.clubCoin = clubUnionCoin;

            //组织一个字符串
            let fName = '俱乐部';
            if(coinAmount > 0){
                fName = fName +'(' + clubId + ') 给玩家 ' +'(' + memberId + ') ' + coinAmount +'分数，俱乐部-' + coinAmount + '分数';
            }else{
                fName = fName +'(' + clubId + ') 给玩家 ' +'(' + memberId + ') ' + coinAmount +'分数，俱乐部+' + -coinAmount + '分数';
            }


            sql = 'update clubinfo set unionCoin = ? , coin_event = 2, logEvent = ? where clubId = ? ';
            args = [clubUnionCoin, fName, clubId]
            await conn.query(sql, args);

            sql = 'update clubinfo set coin_event = null where clubId = ? ';

            args = [clubId]
            await conn.query(sql, args);
            return true;
        }).catch(e =>{
            if(e instanceof BusiError){
                throw e;
            }
            return false;
        });


    }

    //新增微信用户
    async addWxUser(user){
        let sql = 'select max(Id) FROM users';
        let res= await mysqlPool.query(sql,[]);
        let uid=res[0]['max(Id)']+100000;
        sql = 'insert into users (account,name,wxNickName,headimgurl,sex,lastLoginTick,uid,registerDate,registerIp) values(?,?,?,?,?,?,?,?,?)';

        let loginTime = new Date().getTime();
        let args = [user.account, user.name, user.wxNickName, user.headimgurl, user.sex,loginTime, uid, new Date(), user.ip];
        if(user.unionid !== undefined) {
            sql = 'insert into users (account,name,wxNickName,headimgurl,sex,lastLoginTick,uid,registerDate,registerIp,weixinUid) values(?,?,?,?,?,?,?,?,?,?)';
            args = [user.account, user.name, user.wxNickName, user.headimgurl, user.sex, loginTime, uid, new Date(), user.ip, user.unionid];
        }
        console.logw('插入微信玩家信息 users ',args);
        res = await mysqlPool.query(sql,args);
        if(res) {
            return {suc:true, uid:uid, wxNickName:user.wxNickName};
        }
    }


    async addXlUser(user){
        let sql = 'select max(Id) FROM users';
        let res= await mysqlPool.query(sql,[]);
        let uid=res[0]['max(Id)']+100000;
        sql = 'insert into users (account,name,headimgurl,lastLoginTick,uid,registerDate) values(?,?,?,?,?,?)';

        let loginTime = new Date().getTime();
        let args = [user.account, user.name, user.headimgurl,loginTime, uid, new Date()];

        console.logw('插入闲聊玩家信息 users ',args);
        res = await mysqlPool.query(sql,args);
        if(res) {
            return {suc:true, uid:uid};
        }
    }

    //修改微信用户
    async updateWxUser(user){
        if(user === undefined){
            return false;
        }
        let sql='update users set name=?, wxNickName=?, headimgurl=?, sex=?, lastLoginTick=? ';
        let args = [user.name, user.wxNickName, user.headimgurl, user.sex, Date.now()];
        if(user.unionid && user.unionid !== undefined) {
            sql = sql + ', weixinUid = ? ';
            args.push(user.unionid);
        }
        sql = sql + 'where id = ?';
        args.push(user.Id);
        console.logw('更新微信玩家信息 users', sql, args);
        let  res = await mysqlPool.query(sql,args);
        return res;
    }


    async updateXlUser(user){
        if(user === undefined){
            return false;
        }
        let sql='update users set name=?, headimgurl=?, lastLoginTick=? ';
        let args = [user.name, user.headimgurl, Date.now()];
        sql = sql + 'where id = ?';
        args.push(user.Id);
        console.logw('更新闲聊玩家信息 users', sql, args);
        let  res = await mysqlPool.query(sql,args);
        return res;
    }

    async getUserByWx (account){
        let sql = 'select * from  users where account= ? or weixinUid= ?';
        let args=[account,account];
        let res = await mysqlPool.queryAsync(sql,args);
        if(res) {
            let len=res.length;
            if(len === 0) return null;
            return res[0];
        }
        return null;
    }

    async updateOpenidByUnionid(unionid, openid){
        let sql = 'update users set account=? where weixinUid=?';
        if(openid.indexOf("wx_")<0) {
            openid='wx_'+openid;
        }
        let args=[openid,unionid];
        let res=await mysqlPool.query(sql,args);
        return res;
    }

    /**
     * 获取联盟疲劳币的发放记录
     * @param unionId
     * @returns {Promise<*>}
     */
    async unionCoinRecordList(unionId){
        let sql = 'select a.*, b.clubName from union_ucoin_issue_record a left join clubinfo b on a.clubId = b.clubId where a.unionId = ? order by a.create_time desc limit 0, 50';
        let args=[unionId];
        let res = await mysqlPool.query(sql,args);
        return res;
    }

    /**
     * 获取联盟内俱乐部的疲劳币发放记录
     * @param unionId
     * @returns {Promise<*>}
     */
    async unionClubCoinRecordList(unionId){
        let sql = 'select a.*, b.clubName, c.name memberName from club_ucoin_issue_record a left join clubinfo b on a.clubId = b.clubId left join users c on a.memberId= c.uid where b.unionId = ? and a.event_type = 1 order by a.create_time desc limit 0, 50';
        let args=[unionId];
        let res = await mysqlPool.query(sql,args);
        return res;
    }

    async clubUnionRecordList(clubId){
        let sql = 'select * from club_ucoin_issue_record  where clubId = ? and event_type = 1 order by create_time desc limit 0, 50';
        let args=[clubId];
        let res = await mysqlPool.query(sql,args);
        return res;
    }
    async judgeUnionDeleteAble(unionId, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'select a.* from club  a left join clubinfo b on a.clubId = b.clubId where b.unionId = ? and a.unionCoin != 0 and a.unionCoin is not null ';
        //let sql = 'select * from club  a left join clubinfo b on a.clubId = b.clubId where b.unionId = ? and a.unionCoin != 0 and b.unionCoin != 0 and a.unionCoin is not null and b.unionCoin is not null';
        let args=[unionId];
        let res = await conn.query(sql,args);
        if(!res || res.length > 0){
            return false;
        }
        sql = 'select * from  clubinfo  where unionId = ? and unionCoin != 0 and unionCoin is not null ';
        res = await conn.query(sql,args);
        if(res && res.length === 0){
            console.logw(res);
            return true;
        }
        return false;
    }

    async deleteUnion(unionId, conn){
        if(conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'update unioninfo set del_flag = 1 where unionId = ?';
        let args = [unionId];
        await conn.query(sql, args);
        sql = 'update clubinfo set unionId = ? where unionId = ?';
        args = [null, unionId];
        await conn.query(sql, args);
    }

    async dissolveUnion(unionId){
        await mysqlPool.doWithTx(async (conn) => {
            let delAble = await this.judgeUnionDeleteAble(unionId);
            if(!delAble){
                throw new BusiError(500, '大联盟内有成员疲劳值不为0，不能解散');
            }
            this.deleteUnion(unionId);
        });
    }



    async sendFangka(uid,sendUid,cardNum){
        let  ret = await this.makeGiftCard(uid,cardNum)
        if(ret&ret.suc === 0) {
            return null;
        }
        ret=await  this.getGiftCard(uid,sendUid,ret.rid)
        return ret;
    }

}

let userDao = new UserDao();
module.exports = userDao;
